package com.laviedesfons.tinapoc.ant;

import jasmin.JasminException;
import jasmin.Main;
import java.io.File;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.resources.FileResource;

/**
 *
 * @author Romano
 */
public class JasminTask extends Task{

    private String outpath;
    private Vector filesets = new Vector();

    public void setOutpath(String location) {
        this.outpath = location;
    }

    public void addFileset(FileSet fileset) {
        filesets.add(fileset);
    }    
    
    @Override
    public void execute(){
        if(outpath == null)
            throw new BuildException("missing required property: outpath");
        File parent = new File(outpath);
        parent.mkdirs();
        if(!(parent.exists() && parent.isDirectory() && parent.canWrite()))
            throw new BuildException("unable to write in directory: "+outpath);    
        if(filesets.isEmpty())
            throw new BuildException("requires at least one fileset to proceed");
        
        Iterator it = filesets.iterator();
        while(it.hasNext()){
            FileSet curIt = (FileSet) it.next();
            Iterator includesIt = curIt.iterator();
            while(includesIt.hasNext()){
                try {
                    FileResource resource = (FileResource) includesIt.next();
                    Logger.getLogger(JasminTask.class.getName()).log(Level.INFO,
                           "assembling class: {0}", resource.getName());
                    Main.assemble(resource.getFile().getAbsolutePath(),parent.getAbsolutePath());
                } catch (JasminException ex) {
                    throw new BuildException(ex.getMessage());
                }
            }
        }
    }
}
